// AR扫描工具类

// 初始化AR扫描器
export const initARScanner = () => {
    // 检查设备是否支持AR
    if (!uni.getSystemInfoSync().platform) {
        uni.showToast({
            title: '当前设备不支持AR功能',
            icon: 'none'
        })
        return false
    }
    return true
}

// 开始AR扫描
export const startARScan = (callback) => {
    // 请求相机权限
    uni.authorize({
        scope: 'scope.camera',
        success: () => {
            // 打开相机
            uni.chooseImage({
                count: 1,
                sourceType: ['camera'],
                success: (res) => {
                    // 处理扫描结果
                    processScanResult(res.tempFilePaths[0], callback)
                },
                fail: () => {
                    uni.showToast({
                        title: '相机启动失败',
                        icon: 'none'
                    })
                }
            })
        },
        fail: () => {
            uni.showToast({
                title: '请授权相机权限',
                icon: 'none'
            })
        }
    })
}

// 处理扫描结果
const processScanResult = (imagePath, callback) => {
    // 上传图片到服务器进行识别
    uni.uploadFile({
        url: '/api/ar/scan',
        filePath: imagePath,
        name: 'image',
        success: (res) => {
            const result = JSON.parse(res.data)
            if (result.success) {
                callback(result.data)
            } else {
                uni.showToast({
                    title: '未识别到宝藏',
                    icon: 'none'
                })
            }
        },
        fail: () => {
            uni.showToast({
                title: '识别失败',
                icon: 'none'
            })
        }
    })
}

// 检查位置权限
export const checkLocationPermission = () => {
    return new Promise((resolve, reject) => {
        uni.authorize({
            scope: 'scope.userLocation',
            success: () => resolve(true),
            fail: () => reject(false)
        })
    })
}

// 获取当前位置
export const getCurrentLocation = () => {
    return new Promise((resolve, reject) => {
        uni.getLocation({
            type: 'gcj02',
            success: (res) => resolve(res),
            fail: () => reject(new Error('获取位置失败'))
        })
    })
}

// 计算两点之间的距离
export const calculateDistance = (lat1, lng1, lat2, lng2) => {
    const R = 6371 // 地球半径，单位km
    const dLat = toRad(lat2 - lat1)
    const dLon = toRad(lng2 - lng1)
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    return R * c
}

// 角度转弧度
const toRad = (d) => {
    return d * Math.PI / 180
}

// 检查是否在指定范围内
export const isInRange = (lat1, lng1, lat2, lng2, range) => {
    const distance = calculateDistance(lat1, lng1, lat2, lng2)
    return distance <= range
}

// 获取附近门店
export const getNearbyStores = (latitude, longitude, radius = 5) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: '/api/store/nearby',
            data: {
                latitude,
                longitude,
                radius
            },
            success: (res) => {
                if (res.data.success) {
                    resolve(res.data.data)
                } else {
                    reject(new Error('获取门店失败'))
                }
            },
            fail: () => reject(new Error('网络请求失败'))
        })
    })
}

// 检查宝藏是否已被发现
export const checkTreasureFound = (treasureId) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: '/api/treasure/check',
            data: { treasureId },
            success: (res) => {
                if (res.data.success) {
                    resolve(res.data.data)
                } else {
                    reject(new Error('检查失败'))
                }
            },
            fail: () => reject(new Error('网络请求失败'))
        })
    })
}

// 记录宝藏发现
export const recordTreasureFound = (treasureId) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: '/api/treasure/found',
            method: 'POST',
            data: { treasureId },
            success: (res) => {
                if (res.data.success) {
                    resolve(res.data.data)
                } else {
                    reject(new Error('记录失败'))
                }
            },
            fail: () => reject(new Error('网络请求失败'))
        })
    })
} 